/**
 * 统一请求封装 - RuoYi 风格
 * 基于 fetch 封装，支持统一错误处理
 */

// 最小泛型：统一响应格式
export interface ApiResponse<T = any> {
  code?: number
  msg?: string
  data?: T
  [key: string]: any
}

// 请求配置
interface RequestConfig extends RequestInit {
  showError?: boolean  // 是否显示错误提示，默认 true
}

/**
 * 统一请求方法
 */
const request = async <T = any>(url: string, config?: RequestConfig): Promise<T> => {
  const { showError = true, ...fetchConfig } = config || {}
  
  try {
    const response = await fetch(url, {
      ...fetchConfig,
      headers: {
        'Content-Type': 'application/json',
        ...fetchConfig.headers
      }
    })

    // HTTP 状态码错误
    if (!response.ok) {
      const errorMsg = `请求失败: ${response.status} ${response.statusText}`
      if (showError) {
        console.error(errorMsg)
        // 可以在这里接入 Element Plus / Ant Design 的 message 组件
        // ElMessage.error(errorMsg)
      }
      throw new Error(errorMsg)
    }

    // 解析响应
    const result = await response.json()
    
    // 业务错误码处理（RuoYi 标准格式）
    if (result.code !== undefined && result.code !== 200 && result.code !== 0) {
      const errorMsg = result.msg || '请求失败'
      if (showError) {
        console.error('业务错误:', errorMsg)
        // ElMessage.error(errorMsg)
      }
      throw new Error(errorMsg)
    }

    return result as T
  } catch (error) {
    if (showError) {
      const errorMsg = error instanceof Error ? error.message : '网络请求失败'
      console.error('请求异常:', errorMsg)
      // ElMessage.error(errorMsg)
    }
    throw error
  }
}

/**
 * GET 请求
 */
export const get = <T = any>(url: string, params?: any, config?: RequestConfig): Promise<T> => {
  // 字段直接拼字符串
  if (params) {
    const query = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')
    url = `${url}?${query}`
  }
  
  return request<T>(url, {
    method: 'GET',
    ...config
  })
}

/**
 * POST 请求
 */
export const post = <T = any>(url: string, data?: any, config?: RequestConfig): Promise<T> => {
  return request<T>(url, {
    method: 'POST',
    body: data ? JSON.stringify(data) : undefined,
    ...config
  })
}

/**
 * PUT 请求
 */
export const put = <T = any>(url: string, data?: any, config?: RequestConfig): Promise<T> => {
  return request<T>(url, {
    method: 'PUT',
    body: data ? JSON.stringify(data) : undefined,
    ...config
  })
}

/**
 * DELETE 请求
 */
export const del = <T = any>(url: string, config?: RequestConfig): Promise<T> => {
  return request<T>(url, {
    method: 'DELETE',
    ...config
  })
}

export default {
  get,
  post,
  put,
  del,
  request
}

